package me.itblog.mvc.filter;

import me.itblog.bean.User;
import org.nutz.json.Json;
import org.nutz.lang.util.NutMap;
import org.nutz.mvc.ActionContext;
import org.nutz.mvc.ActionFilter;
import org.nutz.mvc.View;
import org.nutz.mvc.view.ForwardView;
import org.nutz.mvc.view.VoidView;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 *  管理员验证
 * Created by Administrator on 2015/12/3.
 */
public class AdminAuthcActionFilter implements ActionFilter {
    @Override
    public View match(ActionContext actionContext) {
        HttpServletRequest req = actionContext.getRequest();
        User user = (User) req.getSession().getAttribute("me");
        if (user != null && user.getName().equals("admin")) {
            return null;
        } else {
            //ajax
            if (req.getHeader("x-requested-with") != null
                    && req.getHeader("x-requested-with").equalsIgnoreCase("XMLHttpRequest")) {
                NutMap re = new NutMap().setv("ok", false).setv("msg", "Insufficient permission");
                try {
                    Json.toJson(actionContext.getResponse().getWriter(), re);
                } catch (IOException e) {
                }
                return new VoidView();

            } else {
                return new ForwardView("/");
            }
        }
    }
}
